<?php
use \GatewayWorker\Lib\Db;
require_once 'vendor/autoload.php';
require_once APPPATH.'config/Db.php';
class Device_model extends CI_Model {
	private static  $read_db=null;
	private $dbWorker;
	/**
	 * 获取read_db的数据库连接
	 */
	private  function  read_db(){
		if(empty($read_db)){
			$read_db=$this->load->database('read_db', TRUE);
		}
		return $read_db;
	}
	
	public function __construct()
    {
        parent::__construct();
        $this->load->database();
		$this->dbWorker = Db::instance('db');
    }

    /**
     * @param string $data
     * @result user
     */
    function getDeviceInfo($data){
    	try {
			if(empty($data)){
				return false;
			}
//			$db = Db::instance('db');
			$result = $this->dbWorker->row("SELECT * FROM ca_device WHERE deviceNum='$data' order by id desc limit 1");
//			$query = $this->db->query('SELECT * FROM ca_device WHERE deviceNum='.$this->db->escape($data).' order by id desc limit 1');
//			$result = $query->row();
    	} catch (Exception $e) {
    		log_message('error',  $e->getMessage());
    	}
    	 return $result;
    }


    /**
     * @param string $id
     * @result user
     */
    function update($id){
    	try {
			if(empty($id)){
				return false;
			}
//			$query = $this->db->query('update ca_form_1_device set binding="2" WHERE id='.$this->db->escape($id));
//			$result = $this->db->affected_rows();
			$result = $this->dbWorker->query("update ca_form_1_device set binding='2' WHERE id='$id'");
    	} catch (Exception $e) {
    		log_message('error',  $e->getMessage());
    	}
    	 return $result;
    }


    /**
     * @param string $uid
     * @result user
     */
    function getAll($uid){
    	try {
			if(empty($uid)){
				return false;
			}
//			$query = $this->db->query('select * from ca_form_1_device WHERE uid='.$this->db->escape($uid).' and binding = 1 ');
//			$result = $query->result_array();
			$result = $this->dbWorker->query("select * from ca_form_1_device WHERE uid='$uid' and binding = 1");
    	} catch (Exception $e) {
    		log_message('error',  $e->getMessage());
    	}
    	 return $result;
    }


	/**
	 * @param string $id
	 * @result user
	 */
	function getOne($id){
		try {
			if(empty($id)){
				return false;
			}
//			$query = $this->db->query('SELECT * FROM ca_form_1_device WHERE id='.$this->db->escape($id).' limit 1');
//			$result = $query->row();
			$result = $this->dbWorker->row("SELECT * FROM ca_form_1_device WHERE id='$id' limit 1");
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}

	/**
	 * 根据设备号获取用户uid
	 */
	function getUidByDeviceId($deviceId){
		try {
			if(empty($deviceId)){
				return false;
			}
//			$query = $this->db->query('SELECT * FROM ca_device WHERE deviceNum='.$this->db->escape($deviceId).' limit 1');
//			$result = $query->row();
			$result = $this->dbWorker->row("SELECT * FROM ca_device WHERE deviceNum='$deviceId' limit 1");
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}

	/**
	 * 经纬度入库
	 * @param array $data
	 * @result $result
	 */
	function insertLongLat($data){
		try {
			$time = time();
			$insertData = array(
				'uid' => $data['uid'],
				'device_id' => $data['device_id'],
				'longitude' => $data['longitude'],
				'latitude' => $data['latitude'],
				'create_time' => $time
			);
//			$this->db->insert('ca_long_lat', $insertData);
//			$result = $this->db->insert_id();

			$result = $this->dbWorker->insert('ca_long_lat')->cols($insertData)->query();
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}

	/**
	 * 设备的位置变化是否满足支付广告费（半小时内位移>10m）
	 * @param $deviceId
	 * @return bool
	 */
	function isGiveMoney($deviceId){
		$lastPosition = $this->getDevicePosition($deviceId,'now');	//获取设备最后一条地理位置坐标
		$MinsPosition = $this->getDevicePosition($deviceId,'30min');	//获取30分钟前最后的地理位置坐标

		if(empty($lastPosition)){
			return false;
		}
		if(empty($MinsPosition)){
			return true;
		}
		$lng1 = $lastPosition['longitude'];
		$lat1 = $lastPosition['latitude'];
		$lng2 = $MinsPosition['longitude'];
		$lat2 = $MinsPosition['latitude'];
		$distance = $this->getDistance($lng1,$lat1,$lng2,$lat2);	//求两个已知经纬度之间的距离,单位为米
		if(intval($distance) < 10){
			return false;
		}
		return true;
	}


	/**
	 * 根据设备号获取车辆位置
	 * @param $deviceId
	 * @param $operate
	 * @return array|bool
	 */
	function getDevicePosition($deviceId,$operate){
		try {
			if(empty($deviceId)){
				return false;
			}
			$result = [];
			if($operate == 'now'){
				$time = time() - 10*60;
				$result = $this->dbWorker->row("SELECT * FROM ca_long_lat WHERE device_id='$deviceId' and create_time>'$time' order by id DESC limit 1");
			}else{
				$beginTime = time() - 40*60;
				$endTime = time() - 30*60;
				$result = $this->dbWorker->row("SELECT * FROM ca_long_lat WHERE device_id='$deviceId' and create_time>'$beginTime' and create_time<'$endTime' order by id DESC limit 1");
			}
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}


	/**
	 *求两个已知经纬度之间的距离,单位为米
	 *@param lng1,lng2 经度
	 *@param lat1,lat2 纬度
	 *@return float 距离，单位米
	 *@author www.Alixixi.com
	 **/
	function getDistance($lng1,$lat1,$lng2,$lat2){
		//将角度转为狐度
		$radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度
		$radLat2=deg2rad($lat2);
		$radLng1=deg2rad($lng1);
		$radLng2=deg2rad($lng2);
		$a=$radLat1-$radLat2;
		$b=$radLng1-$radLng2;
		$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000;
		return $s;
	}


    
}